package com.android.tio.tiocloud

import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.android.tio.tiocloud.base.BaseActivity
import com.android.tio.tiocloud.base.BaseApplication.Companion.gson
import com.android.tio.tiocloud.base.BaseApplication.Companion.uuid
import com.android.tio.tiocloud.composes.TopBar
import com.android.tio.tiocloud.models.tio.TioBody
import com.android.tio.tiocloud.models.tio.TioType
import com.android.tio.tiocloud.server.TioServer
import com.android.tio.tiocloud.tio.client.starter.ClientStarter
import com.android.tio.tiocloud.ui.theme.TioCloudTheme
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : BaseActivity() {
    private var tag: String = "MainActivity"

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onMessageEvent(body: String) {
        Log.i(tag, "onMessageEvent: $body")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        uuid = "99999999999999"
        EventBus.getDefault().register(this)
        Thread { ClientStarter.run() }.start()
        setContent {
            TioCloudTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    var modifier=Modifier
                    Main("Android",modifier)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }
}


@Composable
fun Main(name: String, modifier: Modifier = Modifier) {
    Column() {
        TopBar(modifier)
        Text(
            text = "Hello $name!",
            modifier = modifier
        )
        Button(onClick = {
            var text = TioBody.Text()
            text.msg = "自己给自己发送信息，试一试！"
            TioServer.instance.sendToUser(TioType.Text, uuid, gson.toJson(text))

        }) {
            Text(text = "给自己发送信息")
        }
    }

}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    TioCloudTheme {
        Main("Android")
    }
}

